import { View, Canvas } from "@tarojs/components";
import useTiming from "@/hooks/useTiming";
import { CSSProperties, useEffect, useRef } from "react";
import { getSecondsFormat } from "@/utils";
import "./index.less";

import PlayLineIcon from "@/components/Icons/PlayLineIcon";
import PauseLineIcon from "@/components/Icons/PauseLineIcon";
import CheckLineIcon from "@/components/Icons/CheckLineIcon";
import CloseIcon from "@/components/Icons/CloseIcon";
import ResetIcon from "@/components/Icons/ResetIcon";
import SkipIcon from "@/components/Icons/SkipIcon";
import Taro from "@tarojs/taro";

type Props = {
  title: string;
  direction?: "up" | "down";
  initialSeconds?: number; // 初始秒数
  onDone: (seconds?: number) => void;
  onClose?: () => void;
};

const CloseStyle = {
  position: "absolute",
  top: "1rem",
  right: "1rem",
  zIndex: 999,
} as CSSProperties;

const TimingUp = ({ title, onDone, onClose, initialSeconds = 0 }: Props) => {
  const { isRunning, seconds, startTimer, pauseTimer, stopTimer } = useTiming({
    direction: "up",
    initialSeconds,
  });

  useEffect(() => {
    startTimer();
  }, []);

  return (
    <View className="timing">
      <CloseIcon
        style={CloseStyle}
        type="default"
        onClick={() => {
          stopTimer();
          onClose?.();
        }}
        size={1.4}
      />
      <View className="timing-wrapper">
        <View className="timing-title">{title}</View>
        <View className="timing-tick">{getSecondsFormat(seconds)}</View>
        <View className="timing-action">
          {isRunning ? (
            <PauseLineIcon
              type="white"
              circle="warning"
              onClick={pauseTimer}
              size={1.6}
              circleSize={3}
            />
          ) : (
            <PlayLineIcon
              type="white"
              circle="success"
              onClick={startTimer}
              size={1.4}
              circleSize={3}
            />
          )}

          <CheckLineIcon
            size={1.4}
            circleSize={3}
            type="white"
            circle="success"
            onClick={() => {
              stopTimer();
              onDone?.(seconds);
            }}
          />
        </View>
      </View>
    </View>
  );
};

const _default = {
  lineWidth: 2,
  bgColor: "#eee",
  progressColor: "#00adb5",
  doneColor: "#dcedc1",
  textColor: "#eee",
  fontSize: 80,
};
const TimingDown = ({ title, initialSeconds = 30, onDone, onClose }: Props) => {
  const { isRunning, seconds, startTimer, pauseTimer, stopTimer, resetTimer } =
    useTiming({
      direction: "down",
      initialSeconds,
    });

  useEffect(() => {
    initCanvas();
    startTimer();
  }, []);

  useEffect(() => {
    progress(seconds, initialSeconds);
  }, [seconds]);

  const config = useRef({
    centerX: 0,
    centerY: 0,
    radius: 0,
    width: 0,
    height: 0,
  });
  const ctxRef = useRef(null);

  const initCanvas = async () => {
    const query = Taro.createSelectorQuery();
    const dpr = Taro.getSystemInfoSync().pixelRatio;
    query
      .select("#timeCanvas")
      .fields({
        node: true,
        size: true,
      })
      .exec(function (res) {
        const canvas = res[0].node;
        canvas.width = res[0].width * dpr;
        canvas.height = res[0].height * dpr;

        config.current.centerX = canvas.width / 2;
        config.current.centerY = canvas.height / 2;
        config.current.radius = canvas.width / 2;
        config.current.width = canvas.width;
        config.current.height = canvas.height;

        const ctx = canvas.getContext("2d");
        ctxRef.current = ctx;

        progress(seconds, initialSeconds);
      });
  };

  const handleDone = () => {
    if (seconds === 0) {
      onDone?.();
    }
  };

  const progress = (seconds, initialSeconds) => {
    if (ctxRef.current) {
      const ctx = ctxRef.current as CanvasRenderingContext2D;

      ctx.clearRect(0, 0, config.current.width, config.current.height);

      const progress = 1 - seconds / initialSeconds;
      const startAngle = -Math.PI / 2;
      const endAngle = startAngle + Math.PI * 2 * progress;

      // 绘制背景圆
      ctx.beginPath();
      ctx.arc(
        config.current.centerX,
        config.current.centerY,
        config.current.radius,
        0,
        Math.PI * 2
      );
      ctx.strokeStyle = _default.bgColor;
      ctx.lineWidth = _default.lineWidth;
      ctx.stroke();

      // 其他
      ctx.beginPath();
      ctx.moveTo(config.current.centerX, config.current.centerY);
      ctx.arc(
        config.current.centerX,
        config.current.centerY,
        config.current.radius,
        startAngle,
        endAngle
      );
      ctx.lineWidth = _default.lineWidth;
      ctx.lineCap = "round";

      ctx.fillStyle = _default.progressColor;
      ctx.fill();

      // 绘制中心文本
      ctx.font = `bold ${_default.fontSize}px ui-monospace`;
      ctx.textAlign = "center";
      ctx.textBaseline = "middle";
      ctx.fillStyle = _default.textColor;
      ctx.fillText(
        `${seconds === 0 ? "DONE!" : seconds}`,
        config.current.centerX,
        config.current.centerY
      );
    }
  };

  return (
    <View className="timing">
      <CloseIcon
        style={CloseStyle}
        type="default"
        onClick={() => {
          stopTimer();
          onClose?.();
        }}
        size={1.4}
      />
      <View className="timing-wrapper">
        <View className="timing-title">{title}</View>
        <View
          className="flex-center timing-tick"
          style={{ marginTop: Taro.pxTransform(30) }}
        >
          <Canvas
            type="2d"
            id="timeCanvas"
            style={{ width: "50vw", height: "50vw" }}
            onClick={handleDone}
          />
        </View>
        <View className="timing-action">
          {isRunning && (
            <PauseLineIcon
              type="white"
              circle="warning"
              onClick={pauseTimer}
              size={1.6}
              circleSize={3}
            />
          )}

          {!isRunning && seconds !== 0 && (
            <PlayLineIcon
              type="white"
              circle="success"
              onClick={startTimer}
              size={1.4}
              circleSize={3}
            />
          )}

          <SkipIcon
            size={1.4}
            circleSize={3}
            type="white"
            circle="success"
            onClick={() => {
              stopTimer();
              onDone?.();
            }}
          />

          <ResetIcon
            size={1.4}
            circleSize={3}
            type="white"
            circle="default"
            onClick={() => {
              startTimer();
              resetTimer();
            }}
          />
        </View>
      </View>
    </View>
  );
};

export default {
  Up: TimingUp,
  Down: TimingDown,
};
